package sg.edu.nyp.sit.fypj.qms.servlets;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;

import Database.AuditLogDB;
import Database.CommitteeRoleDB;
import Database.StaffDB;
import Model.Committee;
import Model.CommitteeRole;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * Servlet implementation class CommitteePrintAll
 */
@WebServlet(description = "Facilitates printing of collated pdf for committees", urlPatterns = { "/CommitteePrintAll" })
public class CommitteePrintAll extends HttpServlet{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CommitteePrintAll() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		AuditLogDB.insertLog("print committee", (String) request
				.getSession().getAttribute("name"));
		Committee com = new Committee();
		ArrayList<Committee> comList = new ArrayList<Committee>();
		comList = Committee.getApprovedCommittees();
		ArrayList<String> staffList = new ArrayList<String>();
		response.setContentType("application/pdf");
		Document myDocument = new Document(PageSize.A4, 36, 36, 72, 72);
	
		try {
			for(int index = 0; index < comList.size();index++){
				com = comList.get(index);
				ArrayList<CommitteeRole> committeeRoleArr = CommitteeRoleDB.getCommitteeRole(com.getId());
//			myDocument.newPage();
			// Writes particulars into PDF file
			PdfWriter.getInstance(myDocument, response.getOutputStream());

			myDocument.setMarginMirroring(true);

			myDocument.open();
			Font fontbold = new Font();
			fontbold.setSize(10);
			fontbold.setStyle(Font.BOLD);

			Font font = new Font();
			font.setSize(10);
			try{
		
				String imageUrl = "http://" + request.getServerName()+":" + request.getServerPort() + request.getServletContext().getContextPath()+"/images/Official_Logo.jpg";
				System.out.println("Image path: " + imageUrl);
				Image image = Image.getInstance(new URL(imageUrl));
				myDocument.add(image);
			}
			catch(Exception ex){System.out.println(ex);}
			
			// Terms of reference
			myDocument.add(new Paragraph("TERMS OF REFERENCE", fontbold));

			myDocument
					.add(new Paragraph(
							"______________________________________________________________________________",
							font)); // Divider
			// line

			myDocument.add(new Paragraph("     ", font));

			// Committee Title
			Chunk comm_title = new Chunk(com.getTitle(), fontbold);
			comm_title.setUnderline(1f, -2f);
			myDocument.add(comm_title);

			myDocument.add(new Paragraph("     ", font));

			// Role and staff
			PdfPTable table = new PdfPTable(2);
			table.setHorizontalAlignment(Element.ALIGN_LEFT);
			PdfPCell cellOne = new PdfPCell();
			PdfPCell cellTwo = new PdfPCell();

			Chunk role;
			Chunk staff = new Chunk();
			for (int i = 0; i < committeeRoleArr.size(); i++) {
				role = new Chunk(committeeRoleArr.get(i).getName() + ":", font);
				cellOne.addElement(role);
				cellOne.setBorder(Rectangle.NO_BORDER);
				table.addCell(cellOne);
				String[] arr = committeeRoleArr.get(i).getStaffName().split(", ");
				for (int k = 0; k < arr.length; k++) {
					staff = new Chunk(
							StaffDB.getStaffNamebyId(arr[k]));
					cellTwo.addElement(staff);
				}

				cellTwo.setBorder(Rectangle.NO_BORDER);
				table.addCell(cellTwo);

				cellTwo = new PdfPCell();
				cellOne = new PdfPCell();
			}
			myDocument.add(table);
			myDocument.add(new Paragraph("     ", font));
			myDocument.add(new Paragraph("     ", font));

			// Purpose
			Chunk Purpose = new Chunk("Purpose", fontbold);
			myDocument.add(Purpose);

			myDocument.add(new Paragraph("     ", font));
			myDocument.add(new Paragraph(com.getPurpose(), font));

			myDocument.add(new Paragraph("     ", font));
			myDocument.add(new Paragraph("     ", font));

			// Roles & Responsibilities
			myDocument.add(new Paragraph("Roles & Responsibilities", fontbold));

			myDocument.add(new Paragraph("     ", font));
			myDocument.add(new Paragraph(com.getRolesResponsibility(), font));

			myDocument.add(new Paragraph("     ", font));
			myDocument.add(new Paragraph("     ", font));

			// frequency of meeting
			if (!com.getFrequencyOfMeeting().equals("")) {
				Chunk fom = new Chunk(
						"Frequency of Meeting:\u00a0\u00a0\u00a0\u00a0",
						fontbold);
				myDocument.add(fom);
				Chunk fomC = new Chunk(com.getFrequencyOfMeeting(), font);
				myDocument.add(fomC);
				myDocument.add(new Paragraph("     ", font));
				myDocument.add(new Paragraph("     ", font));
			}

			myDocument.add(new Paragraph(
					"Approved by:  ___________________________________", font));

			myDocument
					.add(new Paragraph(
							"                       Director, School Of Information Technology",
							font));

			myDocument.add(new Paragraph("     ", font));

			myDocument.add(new Paragraph("Effective Date: "
					+ formatdate(com.getDate()), font));

			myDocument.add(new Paragraph("     ", font));

			Font f = new Font();
			f.setColor(BaseColor.BLUE);
			f.setStyle(Font.ITALIC);
			f.setSize(10);

			myDocument.add(new Paragraph("     ", font));
			myDocument.add(new Paragraph("     ", font));
			myDocument
					.add(new Paragraph(
							"This is a computer generated copy, no signature is required.",
							f));
			
			}
		} catch (DocumentException de) {
			System.err.println(de.getMessage());
		} catch (IOException ioe) {
			System.err.println(ioe.getMessage());
		}

		myDocument.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}
	
	private String formatdate(String date) {
		String result = date.split(" ")[0] + " " + date.split(" ")[1].charAt(0)
				+ date.split(" ")[1].substring(1).toLowerCase() + " "
				+ date.split(" ")[2];
		return result;
	}
}
